<template>
    <div class="login-container">
        <div class="login-box">
            <div class="title-container">
                <h2 class="title">智仓通管理</h2>
                <p class="subtitle">Warehouse Management System</p>
            </div>
            <el-form class="login-form" :model="form" ref="loginform" :rules="rules">
                <el-form-item prop="useraccount">
                    <el-input placeholder="请输入用户账号" v-model="form.useraccount"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input placeholder="请输入密码" type="password" v-model="form.password"></el-input>
                </el-form-item>
                <el-form-item prop="captcha">
                    <el-input placeholder="请输入校验码" style="width: 170px" v-model="form.captcha"></el-input>
                    <canvas id="captcha-canvas" @click="RefreshCaptcha()" width="120" height="40" title="看不清？点击刷新"></canvas>
                </el-form-item>
                <el-form-item>
                    <el-button class="login-button" @click="DengLu()">登录</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="area" >
            <ul class="circles">
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
            </ul>
    </div >
    </div>
</template>

<script>
import {reactive,ref,onMounted} from 'vue';
import { useRouter } from 'vue-router';//路由
import { ElMessage, ElLoading } from 'element-plus'; //提示信息和加载服务
import axios from 'axios';
import http from '../auth/index';
export default {
setup()
    {
        const router = useRouter();//路由
        //表单信息
        const form=reactive({
            useraccount:"",
            password:"",
            captcha:""
        });

        //验证规则
        const loginform=ref("");
        const rules=reactive({  
            useraccount:[
                {required: true, message: '请输入用户账号', trigger: 'blur'}
            ],
            password:[
                {required: true, message: '请输入用户密码', trigger: 'blur'}
            ],
            captcha:[
                {required: true, message: '请输入校验码', trigger: 'blur'}
            ]
        });

        //校验码
        const captchaText=ref("");

        function randomColor(min, max) {
            const r = Math.floor(Math.random() * (max - min) + min);
            const g = Math.floor(Math.random() * (max - min) + min);
            const b = Math.floor(Math.random() * (max - min) + min);
            return `rgb(${r},${g},${b})`;
        }
        //生成校验码
        function RefreshCaptcha(){
            const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            let captcha = '';
            for (let i = 0; i < 4; i++) {
                captcha += chars.charAt(Math.floor(Math.random() * chars.length));
            }
            captchaText.value = captcha;

            const canvas = document.getElementById('captcha-canvas');
            if (!canvas || !canvas.getContext) return;

            const ctx = canvas.getContext('2d');
            const { width, height } = canvas;

            // Background
            ctx.fillStyle = randomColor(240, 255);
            ctx.fillRect(0, 0, width, height);

            // Draw chars
            for (let i = 0; i < captcha.length; i++) {
                const char = captcha[i];
                ctx.font = `bold ${Math.floor(Math.random() * 10 + 25)}px Arial`;
                ctx.fillStyle = randomColor(50, 150);
                ctx.textBaseline = "middle";
                const x = width / 5 * (i + 1) * 0.85;
                const y = height / 2 + (Math.random() * 10 - 5);
                const angle = (Math.random() - 0.5) * Math.PI / 6; // in radians, limit to 30 degrees
                
                ctx.save();
                ctx.translate(x, y);
                ctx.rotate(angle);
                ctx.fillText(char, 0, 0);
                ctx.restore();
            }

            // Noise lines
            for (let i = 0; i < 3; i++) {
                ctx.strokeStyle = randomColor(90, 180);
                ctx.beginPath();
                ctx.moveTo(Math.random() * width, Math.random() * height);
                ctx.lineTo(Math.random() * width, Math.random() * height);
                ctx.stroke();
            }

            // Noise dots
            for (let i = 0; i < 20; i++) {
                ctx.fillStyle = randomColor(100, 200);
                ctx.beginPath();
                ctx.arc(Math.random() * width, Math.random() * height, 1, 0, Math.PI * 2);
                ctx.fill();
            }
        }

        //挂载
        onMounted(() => {
            RefreshCaptcha();
        });


        //登录
        function DengLu(){
            loginform.value.validate((valid)=>{
                if(valid){
                    //创建全屏加载
                    const loadingInstance = ElLoading.service({
                        lock: true,
                        text: '登录中...',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });
                    
                    //获取token令牌
                    axios.get("http://localhost:5178/api/Authoize",{
                        params:{
                            account:form.useraccount,
                            pwd:form.password
                        }
                    }).then(res=>{
                        if(res.data==""){
                            ElMessage.error('用户名或密码错误，请重新登录.')
                            loadingInstance.close();
                            return;
                        }else{
                            //存入token令牌
                            sessionStorage.setItem("token", res.data);
                            //进行登录
                            http.get("/User/GetUser",{
                                params:{
                                    account: form.useraccount,
                                    pwd: form.password
                                }
                            }).then((res)=>{
                                //判断校验码
                                if(form.captcha.toLowerCase() !== captchaText.value.toLowerCase()){
                                    ElMessage.error('校验码有误.')
                                    loadingInstance.close();
                                    return
                                }
                                //存入用户id和角色id
                                sessionStorage.setItem("userid", res.data.user_id);
                                sessionStorage.setItem("roleid", res.data.role_id);
                                //跳转主页
                                router.push("/main")
                                loadingInstance.close();
                            }).catch((error) => {
                                ElMessage.error('登录失败，请重试.')
                                loadingInstance.close();
                            })
                        }
                    }).catch((error) => {
                        ElMessage.error('网络错误，请检查网络连接.')
                        loadingInstance.close();
                    })
                }
            })
        }

        return{
            DengLu,
            form,
            loginform,
            rules,
            RefreshCaptcha
        }
    }
}
</script>

<style scoped>
/* 登录背景 */
.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background: #4e54c8;
    background: -webkit-linear-gradient(to left, #8f94fb, #4e54c8);
    position: relative;
    overflow: hidden;
    background: linear-gradient(135deg, #28b485, #7dd56f);
}

.area{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 0;
}

.circles{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    margin: 0;
    padding: 0;
}

.circles li{
    position: absolute;
    display: block;
    list-style: none;
    width: 20px;
    height: 20px;
    background: rgba(255, 255, 255, 0.2);
    animation: animate 25s linear infinite;
    bottom: -150px;
    
}

.circles li:nth-child(1){
    left: 25%;
    width: 80px;
    height: 80px;
    animation-delay: 0s;
}


.circles li:nth-child(2){
    left: 10%;
    width: 20px;
    height: 20px;
    animation-delay: 2s;
    animation-duration: 12s;
}

.circles li:nth-child(3){
    left: 70%;
    width: 20px;
    height: 20px;
    animation-delay: 4s;
}

.circles li:nth-child(4){
    left: 40%;
    width: 60px;
    height: 60px;
    animation-delay: 0s;
    animation-duration: 18s;
}

.circles li:nth-child(5){
    left: 65%;
    width: 20px;
    height: 20px;
    animation-delay: 0s;
}

.circles li:nth-child(6){
    left: 75%;
    width: 110px;
    height: 110px;
    animation-delay: 3s;
}

.circles li:nth-child(7){
    left: 35%;
    width: 150px;
    height: 150px;
    animation-delay: 7s;
}

.circles li:nth-child(8){
    left: 50%;
    width: 25px;
    height: 25px;
    animation-delay: 15s;
    animation-duration: 45s;
}

.circles li:nth-child(9){
    left: 20%;
    width: 15px;
    height: 15px;
    animation-delay: 2s;
    animation-duration: 35s;
}

.circles li:nth-child(10){
    left: 85%;
    width: 150px;
    height: 150px;
    animation-delay: 0s;
    animation-duration: 11s;
}

@keyframes animate {

    0%{
        transform: translateY(0) rotate(0deg);
        opacity: 1;
        border-radius: 0;
    }

    100%{
        transform: translateY(-1000px) rotate(720deg);
        opacity: 0;
        border-radius: 50%;
    }

}

/* 登录框 */
.login-box {
    background-color: rgba(255, 255, 255, 0.3);
    border-radius: 8px;
    text-align: center;
    width: 400px;
    height: 400px;
    z-index: 1;
}

.title-container {
    padding-top: 50px;
    color: white;
}
.title {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 5px;
}
.subtitle {
    font-size: 14px;
    margin-top: 0;
}

/* 登录表单 */
.login-form {
  width: 300px;
  margin: 0px auto;
  padding: 20px;
}

#captcha-canvas {
  margin-left: 10px;
  vertical-align: middle;
  cursor: pointer;
  border-radius: 4px;
}

/* 登录按钮 */
.login-button {
  width: 100%; 
  height: 40px;
  border-radius: 10px;
}
</style>